<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="queryInfo.query"
            @clear="getUserList()"
          >
            <el-button
              slot='append'
              icon='el-icon-search'
              @click="getUserList()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type='primary'
            @click="dialogVisible = true"
          >添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        :data="userList"
        border
        stripe
      >
        <el-table-column type='index'></el-table-column>

        <el-table-column
          prop='username'
          label='姓名'
        ></el-table-column>
        <el-table-column
          prop='email'
          label='邮箱'
        ></el-table-column>
        <el-table-column
          prop='mobile'
          label='手机号'
        ></el-table-column>
        <el-table-column
          prop='role_name'
          label='角色'
        ></el-table-column>
        <el-table-column label='状态'>
          <!-- 通过作用域插槽 day03 的组件化开发 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="UserstateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label='操作'
          width="180px"
        >
          <template slot-scope='scope'>
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row)"
            ></el-button>
            <!-- 分配角色按钮· -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRolesDialog(scope.row)"
              ></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="70%"
      @close="dialogVisibled"
    >
      <!-- 主体区域 -->
      <el-form
        :model="userForm"
        :rules="userFormRules"
        ref="userForm"
        label-width="100px"
      >
        <el-form-item
          label="姓名"
          prop="username"
        >
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="alterVisible"
      width="70%"
      @close="editCloseDialog"
    >
      <!-- 主体区域 -->
      <el-form
        :model="alterForm"
        :rules="alterFormRules"
        ref="alterForm"
        label-width="100px"
      >
        <el-form-item
          label="姓名"
          prop="username"
        >
          <el-input
            v-model="alterForm.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="alterForm.mobile"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="alterForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="alterVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="eiitUserInfo"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="giveRoleVisible"
      width="70%"
      @close="giveRoleDialog"
    >
      <!-- 主体区域 -->
      <el-form
        :model="giveRoleForm"
        ref="giveRoleForm"
        label-width="100px"
      >
        <div>
          <p>当前的账号：{{giveRoleForm.username}}</p>
          <p>当前的账号：{{giveRoleForm.role_name}}</p>
          <p>分配新角色：
            <el-select
              v-model="selectId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
      </el-form>
      <!-- 尾部区域 -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="giveRoleVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitRole"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // z自定义校验规则
    var checkEmail = (rule, value, cb) => {
      // 邮箱校验规则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      // 手机号校验规则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前页
        pagenum: 1,
        // 每页条目数
        pagesize: 5
      },
      // 总数
      total: 0,
      // 用户列表
      userList: [],
      // 控制对话框的显示和隐藏
      dialogVisible: false,
      // 控制修改用户信息的对话框
      alterVisible: false,
      // 提交的用户信息
      userForm: {
        'username': '',
        'password': '',
        'mobile': '',
        'email': ''
      },
      // 用户信息的验证规则
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      // 修改用户信息
      alterForm: {
        username: '',
        mobile: '',
        email: ''
      },
      // 用户信息的验证规则
      alterFormRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      // 分配角色
      giveRoleVisible: false,
      giveRoleForm: {},
      rolesList: [],
      selectId: ''

    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: result } = await this.$http.get('users', { params: this.queryInfo })
      if (result.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.total = result.data.total
      this.userList = result.data.users
      console.log(this.userList)
    },
    // 最大页数改变
    handleSizeChange(pagesize) {
      console.log(pagesize)
      this.queryInfo.pagesize = pagesize
      this.getUserList()
    },
    // 当前页数改变
    handleCurrentChange(pagenum) {
      console.log(pagenum)
      this.queryInfo.pagenum = pagenum

      this.getUserList()
    },
    // 用户状态改变 使用模板字符串
    async UserstateChange(scope) {
      const { data: result } = await this.$http.put(`users/${scope.id}/state/${scope.mg_state}`)
      console.log(result)
      if (result.meta.status !== 200) return this.$message.error('修改用户状态失败')
      this.$message.success('修改用户状态成功')
    },
    // 添加用户按钮
    addUser() {
      console.log(this)
      this.$refs['userForm'].validate(async (valid) => {
        if (!valid) return this.$message.error('请检查填写的信息')
        const { data: result } = await this.$http.post('users', this.userForm)
        // 创建成功是 201 状态码
        if (result.meta.status !== 201) return this.$message.error(result.meta.msg)
        this.$message.success('用户添加成功')
        this.$refs['userForm'].resetFields()
      })
    },
    // 隐藏 添加用户对话框
    dialogVisibled() {
      this.$refs.userForm.resetFields()

      // 添加用户对话框
      this.dialogVisible = false
      // 修改用户信息对话框
    },
    // 修改用户信息对话框
    async showEditDialog(scope) {
      console.log(scope)
      const { data: result } = await this.$http.get(`users/${scope.id}`)
      if (result.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.alterForm = result.data
      console.log(result.data)
      this.alterVisible = true
    },
    // 修改用户信息对话框关闭
    editCloseDialog() {
      console.log(this.alterForm)
      this.$refs.alterForm.resetFields()
      this.alterVisible = false
    },
    // 校验并提交用户信息
    eiitUserInfo() {
      this.$refs.alterForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请检查修改的信息')
        // 发起网络请求 修改用户信息数据
        const { data: result } = await this.$http.put('users/' + this.alterForm.id, { email: this.alterForm.email, mobile: this.alterForm.mobile })
        if (result.meta.status !== 200) return this.$message.error('用户信息修改失败')
        this.alterVisible = false
        this.$message.success('用户信息修改成功')
        this.getUserList()
      })
    },
    // 删除提示框
    async deleteUser(row) {
      const confirm = await this.$confirm(`此操作将永久删除该用户 ${row.username}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirm)
      if (confirm !== 'confirm') return this.$message.info('用户取消删除')
      const { data: result } = await this.$http.delete(`users/${row.id}`)
      if (result.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 展示分配角色
    async showRolesDialog(row) {
      this.giveRoleForm = row
      // 获取所有的角色列表
      const { data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = result.data
      this.giveRoleVisible = true
      console.log(result.data)
    },
    // 关闭分配角色对话框
    giveRoleDialog() {
      console.log('关闭分配角色')
      this.giveRoleForm = {
      }
      this.selectId = ''
    },
    // 提交分配角色修改信息
    async submitRole() {
      const { data: result } = await this.$http.put(`users/${this.giveRoleForm.id}/role`, { rid: this.selectId })
      if (result.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success(result.meta.msg)
      this.giveRoleVisible = false
      this.getUserList()
    }
  }
}
</script>
<style lang="less" scoped>

</style>
